package com.jzo2o.foundations.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.foundations.enums.FoundationStatusEnum;
import com.jzo2o.foundations.mapper.RegionMapper;
import com.jzo2o.foundations.mapper.ServeItemMapper;
import com.jzo2o.foundations.mapper.ServeMapper;
import com.jzo2o.foundations.model.domain.Region;
import com.jzo2o.foundations.model.domain.Serve;
import com.jzo2o.foundations.model.domain.ServeItem;
import com.jzo2o.foundations.model.dto.request.ServePageQueryReqDTO;
import com.jzo2o.foundations.model.dto.request.ServeUpsertReqDTO;
import com.jzo2o.foundations.model.dto.response.ServeResDTO;
import com.jzo2o.foundations.service.IServeService;
import com.jzo2o.mysql.utils.PageHelperUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
 * @Author: Zuo
 * @Date: 2025/3/20 19:35
 * @Description:
 **/
@Service
public class ServeServiceImpl extends ServiceImpl<ServeMapper, Serve> implements IServeService {

    @Resource
    private ServeItemMapper serveItemMapper;

    @Resource
    private RegionMapper regionMapper;

    @Override
    public PageResult<ServeResDTO> page(ServePageQueryReqDTO servePageQueryReqDTO) {
        //根据区域id查询区域服务列表
        PageResult<ServeResDTO> serveResDTOPageResult =
                PageHelperUtils.selectPage(servePageQueryReqDTO,() -> baseMapper.queryServeListByRegionId(servePageQueryReqDTO.getRegionId()));
        return serveResDTOPageResult;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batch(List<ServeUpsertReqDTO> serveUpsertReqDTOList) {
        if (ObjectUtil.isEmpty(serveUpsertReqDTOList)){
            throw new RuntimeException("服务列表不能为空");
        }
        //遍历区域服务
        for (ServeUpsertReqDTO serveUpsertReqDTO : serveUpsertReqDTOList) {
            //1校验服务项是否为启用状态，不是启用状态不能新增
            LambdaQueryWrapper<ServeItem> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(ServeItem::getId,serveUpsertReqDTO.getServeItemId());
            ServeItem serveItem = serveItemMapper.selectOne(lambdaQueryWrapper);
            if (ObjectUtil.isEmpty(serveItem)){
                throw new RuntimeException("服务项不存在");
            }
            if (!serveItem.getActiveStatus().equals(FoundationStatusEnum.ENABLE.getStatus())){
                throw new ForbiddenOperationException("服务项不是启用状态，不能新增");
            }

            //2.校验服务项是否存在，存在则更新，不存在则新增
            List<Serve> queryList = lambdaQuery()
                    .eq(Serve::getServeItemId,serveUpsertReqDTO.getServeItemId())
                    .eq(Serve::getRegionId,serveUpsertReqDTO.getRegionId())
                    .list();

            if (ObjectUtil.isNotEmpty(queryList)){
                throw new ForbiddenOperationException("服务项已经在该区域下存在，不能新增");
            }

            //新增区域服务
            Serve serve = BeanUtil.toBean(serveUpsertReqDTO, Serve.class);
            //查询下一区域的城市编码
            Region region = regionMapper.selectById(serveUpsertReqDTO.getRegionId());
            if (ObjectUtil.isNotEmpty(region)){
                //设置区域服务的编码
                serve.setCityCode(region.getCityCode());
            }
            //新增区域服务
            baseMapper.insert(serve);
        }

    }

    @Override
    public void updatePrice(Long id, BigDecimal price) {
        if (ObjectUtil.isEmpty(id)){
            throw new ForbiddenOperationException("区域服务id不能为空");
        }
        //1、根据区域服务id 查询区域服务
        Serve serve = baseMapper.selectById(id);
        //校验区域服务是否存在
        if (ObjectUtil.isEmpty(serve)){
            throw new ForbiddenOperationException("区域服务不存在");
        }
        //修改区域服务价格
        serve.setPrice(price);
        baseMapper.updateById(serve);
    }

    @Override
    public void onSale(Long id) {
        //校验参数
        if (ObjectUtil.isEmpty(id)){
            throw new ForbiddenOperationException("区域服务id不能为空");
        }
        //根据区域服务id查询区域服务
        Serve serve = baseMapper.selectById(id);
        //校验区域服务是否存在
        if (ObjectUtil.isEmpty(serve)){
            throw new ForbiddenOperationException("区域服务不存在");
        }
        //判断区域服务是否是草稿或者下架状态
        if (!(serve.getSaleStatus().equals(FoundationStatusEnum.INIT.getStatus()) || serve.getSaleStatus().equals(FoundationStatusEnum.DISABLE.getStatus()))){
            throw new ForbiddenOperationException("区域服务不是草稿或者下架状态，不能上架");
        }
        //查询服务项
        ServeItem serveItem = serveItemMapper.selectById(serve.getServeItemId());
        if (ObjectUtil.isEmpty(serveItem) || !serveItem.getActiveStatus().equals(FoundationStatusEnum.ENABLE.getStatus())){
            throw new ForbiddenOperationException("服务项不存在或者服务项不是启用状态，不能上架");
        }
        //修改区域服务的状态
        boolean update = lambdaUpdate()
                .eq(Serve::getId, id)
                .set(Serve::getSaleStatus, FoundationStatusEnum.ENABLE.getStatus())
                .update();

        if (!update){
            throw new ForbiddenOperationException("区域服务上架失败");
        }
    }

    @Override
    public void offSale(Long id) {
        //校验参数
        if (ObjectUtil.isEmpty(id)){
            throw new ForbiddenOperationException("区域服务id不能为空");
        }
        //根据区域服务id查询区域服务
        Serve serve = baseMapper.selectById(id);
        //校验区域服务是否存在
        if (ObjectUtil.isEmpty(serve)){
            throw new ForbiddenOperationException("区域服务不存在");
        }
        //判断区域服务是否是草稿或者下架状态
        if (!(serve.getSaleStatus().equals(FoundationStatusEnum.INIT.getStatus()) || serve.getSaleStatus().equals(FoundationStatusEnum.ENABLE.getStatus()))){
            throw new ForbiddenOperationException("区域服务不是草稿或者下架状态，不能下架");
        }
        //判断服务项
        ServeItem serveItem = serveItemMapper.selectById(serve.getServeItemId());
        if (ObjectUtil.isEmpty(serveItem) || !serveItem.getActiveStatus().equals(FoundationStatusEnum.ENABLE.getStatus())){
            throw new ForbiddenOperationException("服务项不存在或者服务项不是启用状态，不能下架");
        }
        //循环查询该区域下是否有其他服务项
        Integer count = lambdaQuery().eq(Serve::getServeItemId, serve.getServeItemId())
                .eq(Serve::getSaleStatus, FoundationStatusEnum.ENABLE.getStatus())
                .count();
        if (count <= 0){
            throw new ForbiddenOperationException("区域下至少有一个服务");
        }
        //修改区域服务的状态
        boolean update = lambdaUpdate()
                .eq(Serve::getId, id)
                .set(Serve::getSaleStatus, FoundationStatusEnum.DISABLE.getStatus())
                .update();

        if (!update){
            throw new ForbiddenOperationException("区域服务下架失败");
        }
    }

}
